import 'dart:async';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:rxdart/rxdart.dart';
import 'package:yx_flutter/YXLocalizations.dart';
import 'package:yx_flutter/common/YXSharedPreferencesUtil.dart';

// 添加header认证
class Authinterceptor extends Interceptor {
  @override
  Future onRequest(RequestOptions options) async {
    final token = YXLocalizations.share().token;
    SharedPreferencesUtil.getObjc('Authorization').then((value) {
      String tokenString = value;
      print('tokenString ***** $tokenString');
    });

    options.headers
        .update("Authorization", (_) => token, ifAbsent: () => token);
    return super.onRequest(options);
  }
}

final dio = Dio()
  ..options = BaseOptions(
      baseUrl: 'http://47.100.62.17:8097',
      connectTimeout: 3000,
      receiveTimeout: 3000)
  ..interceptors.add(Authinterceptor())
  ..interceptors.add(LogInterceptor(responseBody: true, requestBody: true));

// 创建future 的get方法
Future _get(String url, Map<String, dynamic> params) async {
  var response = await dio.get(url, queryParameters: params);
  return response.data;
}

// 创建future的post方法
Future _post(String url, Map<String, dynamic> params) async {
  var reponse = await dio.post(url, data: params);
  return reponse.data;
}

// 使用rx调取post请求
Observable post(String url, Map<String, dynamic> params) =>
    Observable.fromFuture(_post(url, params)).asBroadcastStream();

// 使用rx调取get请求
Observable get(String url, Map<String, dynamic> params) =>
    Observable.fromFuture(_get(url, params)).asBroadcastStream();
